<%@ Page Language="c#" ContentType="text/html" ResponseEncoding="utf-8" %>
<script runat="server">
	int maxsize = 4096;
	string noext = ".exe,.bat,.com,.cgi,.dll";
	string img_ext = ".gif,.jpg,.bmp,.tif,.png";
	string _uperror = "";
	public string pubBase = "";
	public string istanzaJS ="";
	public string execJS ="";	
	public string mW="800";
	public string mH ="600";
	
	private string AllowedExtentions
	{
		get
		{
			String s = (String)ViewState[this.ID + "AllowedExtentions"];
			return ((s == null) ? String.Empty : s);
		}

		set
		{
			ViewState[this.ID + "AllowedExtentions"] = value;
		}
	}
	private string CurrentKey
	{
		get
		{
			String s = (String)ViewState[this.ID + "FileKey"];
			return ((s == null) ? String.Empty : s);
		}

		set
		{
			ViewState[this.ID + "FileKey"] = value;
		}
	}


	private string MaxWidth
	{
		get
		{
			String s = (String)ViewState[this.ID + "MaxWidth"];
			return ((s == null) ? mW : s);
		}

		set
		{
			ViewState[this.ID + "MaxWidth"] = value;
		}
	}
	private string MaxHeight
	{
		get
		{
			String s = (String)ViewState[this.ID + "MaxHeight"];
			return ((s == null) ? mH : s);
		}

		set
		{
			ViewState[this.ID + "MaxHeight"] = value;
		}
	}	
	void Page_Load(object o, EventArgs e ) {

		if(Request.Params["source"]!=null) 
			istanzaJS = Request.Params["source"].ToString();
		else
			istanzaJS = "nowork";
		if(istanzaJS.Trim().Length==0) istanzaJS = "nowork";
		if(Request.Params["ope"]!=null) {
			string op = Request.Params["ope"].ToString();
			if(op.ToLower()=="clear") {
				if(Request.Params["key"]==null) return;
				CurrentKey = Request.Params["key"].ToString();
				ClearCache();
			}
		}	
		//AllowedExtentions
		if(Request.Params["exts"]!=null) 
			AllowedExtentions = Request.Params["exts"].ToString();
	
		if(Page.IsPostBack) {
			_uperror="";		
			if (fo_up.HasFile)
			{
				//Controllo size:
				string filename = fo_up.FileName;
				string ext = "";
				if (filename.IndexOf('.') == -1) { _uperror = "NO VALID SOURCE FILE"; return; }
				ext = filename.Substring(filename.LastIndexOf('.'));
				if(AllowedExtentions.Trim().Length>0) {
					if (AllowedExtentions.ToLower().IndexOf(ext.ToLower()) == -1) { _uperror = "NO VALID FILE FORMAT"; return; }
				} else {
					if (noext.IndexOf(ext.ToLower()) != -1) { _uperror = "NO VALID FILE FORMAT"; return; }
				}
				
				byte[] lettore = fo_up.FileBytes;
				
				if (lettore.Length > (maxsize * 1024)) { _uperror = "FILE TOO LONG"; return; }
				
				//se è un img e vogliamo bloccarla al max size previsto dalla configurazione.
				if(img_ext.IndexOf(ext.ToLower())!=-1) {
					//è un IMG la devo resizare:
					try {
						byte[] lettore2 = ACM.cmsarea08.Function.TextClass.textclass.ImageResize(lettore,MaxWidth,MaxHeight);
						lettore = lettore2; 
						_uperror="The image is more bigger than the maximum allowed size, it will be resized.";
					} catch (Exception ex) {
						_uperror="Unable to upload image, file format invalid.\\n" + ex.ToString();
						lettore=new byte[0];
					}
				}
				if(lettore.Length==0) { _uperror = "THE FILE IS AN IMAGE. BUT IT'S TOO BIG."; return; }
				ClearCache();
				
				ACM.cmsarea08.Function.CacheManager.cachemanager.setCacheFileObject(
                	HttpContext.Current,CurrentKey,filename.Replace("#","") +"#" +Convert.ToBase64String(lettore),180,true);
					
//				HttpContext.Current.Cache.Add("DATIIMG" + CurrentKey, lettore, null, DateTime.Now.AddSeconds(180), TimeSpan.Zero, System.Web.Caching.CacheItemPriority.NotRemovable, null);
//				HttpContext.Current.Cache.Add("NAMEIMG" + CurrentKey, filename, null, DateTime.Now.AddSeconds(180), TimeSpan.Zero, System.Web.Caching.CacheItemPriority.NotRemovable, null);
				//_uperror="";
				//pubBase = filename.Replace("#", "") + "#" + Convert.ToBase64String(lettore);
				execJS = ""+
				"try { window.parent."+istanzaJS+".getUploaResponse(\'"+CurrentKey+"\',\'\',\'"+filename+"\',\'"+lettore.Length+ "\'); } catch (errore) { alert(errore); } ";	
				lettore=new byte[0];
				//,'" +_uperror+ "'
			}			
		} else {
			fo_up.Attributes.Add("onchange","javascript:UploadMe();");
		}
	}
	
	
	private void ClearCache()
	{
		if (CurrentKey == "") { CurrentKey = "FILMAN" + System.Guid.NewGuid().ToString(); return; }
		//if (HttpContext.Current.Cache.Get("DATIIMG" + CurrentKey) != null)
		//	HttpContext.Current.Cache.Remove("DATIIMG" + CurrentKey);
		//if (HttpContext.Current.Cache.Get("NAMEIMG" + CurrentKey) != null)
		//	HttpContext.Current.Cache.Remove("NAMEIMG" + CurrentKey);
		ACM.cmsarea08.Function.CacheManager.cachemanager.RemoveCacheFileObject(HttpContext.Current,CurrentKey);
		CurrentKey =  "FILMAN" + System.Guid.NewGuid().ToString();
		return;
	}	
</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Documento senza titolo</title>
<style>
	body {vertical-align:top;}
</style>
<script language="javascript" type="text/javascript">
	function UploadMe() {
		if( '<%=istanzaJS%>' == 'nowork' ) {alert('\'nowork\' word is bad...or there are some problems with the setting'); return; }
		if(window==null) { alert('no window'); return;}
		if(window.parent == null) { alert('no parent'); return;}
		if(window.parent.<%=istanzaJS%>==null) { alert('no object'); return; }
		window.parent.<%=istanzaJS%>.beginUpload();	
		document.forms[0].submit();
	}	
	//quick code for response.
	var errori = '<%=_uperror%>';
	if(errori.length>0)
		alert(errori);
	<%=execJS%>
</script>
<head>
<body style="background-color:transparent; margin:0px; padding:0px;" >
<form name="iform" action="" method="post" enctype="multipart/form-data" runat="server">
<asp:FileUpload runat="server" id="fo_up" runat="server" />
<input type="hidden" name="imgnum" />
</form>
</html>